﻿using System;
using UnityEngine;

namespace HurricanePackage
{
    public abstract class UGUILoadWnd<V> : BasicUGUIWnd<V>, ILoadAble
    where V : BasicView
    {
        private readonly LocalResAssetObject m_assetObj;

        public UGUILoadWnd(LocalResAssetObject _assetObj)
        {
            m_assetObj = _assetObj;
        }

        public void Load(Action _doneAction = null)
        {
            Action loadDoneAct = InitWnd;
            loadDoneAct += _doneAction;

            if (m_assetObj != null)
                m_assetObj.Load(loadDoneAct);
        }

        protected override void InitWnd()
        {
            if (m_assetObj != null)
            {
                //绑定组件
                V view = m_assetObj.GameObj.GetComponent<V>();
                if (view == null)
                {
                    Debug.LogError($"{m_assetObj.AssetName}的VIEW:{typeof(V).Name}未找到");
                    return;
                }
                else
                {
                    //绑定
                    _BandComponents(view);
                }
                //设置加载位置
                if (ParentTransform == null)
                {
                    Debug.LogError($"{m_assetObj.AssetName}的父节点为空");
                    View.transform.SetParent(ParentTransform);
                }
                else
                {
                    View.transform.SetParent(ParentTransform);
                    view.transform.localScale = Vector3.one;
                }
                _OnInitDone();
                m_isInit = true;
            }

        }

        public override void ShowWnd()
        {
            //如果还未初始化
            if (!m_isInit)
                InitWnd();

            m_gameObj?.SetActive(true);
            m_isShow = true;
            _OnShow();
        }

        public override void HideWnd()
        {
            if (!m_isInit || !m_isShow)
                return;


            m_gameObj?.SetActive(false);
            m_isShow = false;
            _OnHide();
        }

        public override void ResetWnd()
        {
            if (!m_isInit)
                return;

            _OnReset();
        }

        public override void DiscordWnd()
        {
            DiscordWnd(null);
        }

        public void DiscordWnd(Action _doAction)
        {
            if (!m_isInit)
                return;

            HideWnd();

            _OnDiscord();
            Destroy(null);
        }

        public void Destroy(Action _doAction)
        {
            m_assetObj.Destroy(_doAction);
        }

        public GameObject GameObj
        {
            get => GetGameObj();
        }
    }
}